package pbc.gx.ekp.addressbook.interceptor;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import pbc.gx.ekp.addressbook.utils.OrgIds;
import pbc.gx.ekp.addressbook.utils.SecurityUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * <p>
 * OAuth2 认证拦截器
 * </p>
 *
 * @author Wang Chen Chen<932560435@qq.com>
 * @version 1.0
 * @createTime 2020/5/30 0030 17:25
 */

@Slf4j
@Component
public class ServerInterceptor implements HandlerInterceptor {
    @Value("${oauth.userInfoURL}")
    private String userInfoURL;

    @Autowired
    private OrgIds orgIds;


    @Autowired
    private RestTemplate restTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //token拦截
        /*String token = request.getHeader("token");
        //log.info("token:" + token);
        JsonNode rs = null;
        if (StringUtils.isNotBlank(token)) {
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
            headers.add("Authorization", "Bearer " + token);

            ResponseEntity<JsonNode> res = restTemplate.exchange(
                    userInfoURL + "?access_token=" + token,
                    HttpMethod.POST,
                    new HttpEntity<String>(headers),
                    JsonNode.class
            );
            rs = res.getBody();
            //log.info(rs.toString());
            if (rs.has("status")) {
                if (rs.get("status").asInt() == 200) {
                    String userId = rs.get("data").get("user").get("mobile").asText();
                    //log.info("userId:" + userId);
                    SecurityUtils.setUserId(userId);
                    return true;
                }
            } else if (rs.has("ret")) {
                if (rs.get("ret").asInt() == 0) {
                    String userId = rs.get("uid").asText();
                    //log.info("userId:" + userId);
                    SecurityUtils.setUserId(userId);
                    return true;
                }
            }
        }
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        String json = rs != null ? rs.toString() : "";
        response.getWriter().print(json);
        return false;
         */
        String orgTag = request.getHeader("orgTag");
        if (orgTag.startsWith("/")) {
            orgTag = orgTag.substring(1, orgTag.length());
        }
        String orgId = orgIds.getMap().get(orgTag + "Id");
        //log.info("orgTag:" + orgTag);
        //log.info("orgId:" + orgId);
        if (StringUtils.isNotBlank(orgId)) {
            SecurityUtils.setOrgId(orgId);
            return true;
        } else {
            response.setStatus(HttpStatus.NO_CONTENT.value());
            return false;
        }

    }
}
